<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%" top="5vh">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.KF_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="对口院校" prop="selectedSchools">
        <el-cascader
          v-model="formData.selectedSchools"
          :options="options"
          :props="cascaderProps"
          collapse-tags
          collapse-tags-tooltip
          clearable
          filterable
          :show-all-levels="false"
          placeholder="请选择或搜索院校"
          @change="handleSchoolsChange"
          style="width: 100%"
        />
      </el-form-item>
      <!-- 隐藏的学校名称字符串 -->
      <el-form-item prop="schools" v-show="false">
        <el-input v-model="formData.schools" hidden />
      </el-form-item>
      <!-- 隐藏的学校ID字符串 -->
      <el-form-item prop="schoolIds" v-show="false">
        <el-input v-model="formData.schoolIds" hidden />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { EmploymentDirApi, EmploymentDirVO } from '@/api/kf/employmentdir'
import { SchoolApi } from '@/api/kf/school'

/** 就业方向 表单 */
defineOptions({ name: 'EmploymentDirForm' })
const cascaderProps = { 
  multiple: true,
  emitPath: true,
  value: 'value',
  label: 'label',
  children: 'children'
}
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
// 定义表单数据类型
interface FormDataType {
  id?: number
  name?: string
  schools?: string // 选中学校名称的逗号分隔字符串
  schoolIds?: string // 选中学校ID的逗号分隔字符串
  selectedSchools: (string | number)[][] // 修改类型定义
  status?: number
  sort?: number
}

const formData = ref<FormDataType>({
  id: undefined,
  name: undefined,
  schools: undefined, // 选中学校名称的逗号分隔字符串
  schoolIds: undefined, // 选中学校ID的逗号分隔字符串
  selectedSchools: [], // 选中的学校数组，用于级联选择器
  status: 1, // 默认选中“已发布”
  sort: undefined
})

const formRules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  selectedSchools: [
    { required: true, message: '请选择对口院校', trigger: 'change' }
  ]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获取院校数据
  await fetchSchoolOptions()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await EmploymentDirApi.getEmploymentDir(id)
      formData.value = data
      
      // 如果有已选择的学校，转换回级联选择器需要的格式
      if (data.schoolIds) {
        try {
          const ids = data.schoolIds.split(',')
          const selectedPaths = []
          
          // 根据学校ID找到完整的选择路径
          ids.forEach(schoolId => {
            // 遍历所有省份
            options.value.forEach(province => {
              if (province.children) {
                // 在该省份下查找学校
                const schoolIndex = province.children.findIndex(school => school.value.toString() === schoolId.toString())
                if (schoolIndex !== -1) {
                  // 找到学校，添加路径
                  selectedPaths.push([province.value, province.children[schoolIndex].value])
                }
              }
            })
          })
          
          formData.value.selectedSchools = selectedPaths
        } catch (e) {
          console.error('解析已选学校失败:', e)
        }
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as EmploymentDirVO
    if (formType.value === 'create') {
      await EmploymentDirApi.createEmploymentDir(data)
      message.success(t('common.createSuccess'))
    } else {
      await EmploymentDirApi.updateEmploymentDir(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 处理学校选择变化 */
const handleSchoolsChange = (values: any[]) => {
  if (!values || values.length === 0) {
    formData.value.schools = undefined;
    formData.value.schoolIds = undefined;
    return;
  }

  // 获取选中的学校的ID和名称
  const ids: (string | number)[] = [];
  const names: string[] = [];

  // 只处理二级路径（[省份, 学校]）
  values.forEach((path: any[]) => {
    if (path.length === 2) {
      const provinceValue = path[0];
      const schoolValue = path[1];
      const province = options.value.find((p: any) => p.value === provinceValue);
      if (province && province.children) {
        const school = province.children.find((s: any) => s.value === schoolValue);
        if (school) {
          ids.push(school.value);
          names.push(school.label);
        }
      }
    }
  });

  formData.value.schoolIds = ids.length > 0 ? ids.join(',') : undefined;
  formData.value.schools = names.length > 0 ? names.join(',') : undefined;
  console.log('学校IDs:', formData.value.schoolIds);
  console.log('学校名称:', formData.value.schools);
}








/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    schools: undefined,
    schoolIds: undefined,
    selectedSchools: [],
    status: 1, // 新增时默认选中“已发布”
    sort: undefined
  } as FormDataType
  formRef.value?.resetFields()
}


// 定义选项数组
// 定义级联选择器选项的类型
interface CascaderOption {
  value: string | number
  label: string
  children?: CascaderOption[]
}

const options = ref<CascaderOption[]>([])

/** 从后端获取院校数据 */
const fetchSchoolOptions = async () => {
  try {
    console.log('开始获取院校数据...')
    const res = await SchoolApi.getAllSchools()
    console.log('原始响应:', res)
    
    // 判断响应是否为数组，直接使用
    if (Array.isArray(res)) {
      options.value = res
      console.log('院校选项数据已设置 (数组格式):', options.value)
      
      if (options.value.length === 0) {
        console.warn('没有找到院校数据')
        message.warning('没有找到院校数据')
      }
    }
    // 判断是否为标准响应格式
    else if (res && res.code === 0 && res.data) {
      options.value = res.data
      console.log('院校选项数据已设置 (标准格式):', options.value)
      
      if (options.value.length === 0) {
        console.warn('没有找到院校数据')
        message.warning('没有找到院校数据')
      }
    } 
    // 其他情况判断为错误
    else {
      console.error('获取院校数据失败:', res)
      message.error('获取院校数据失败')
    }
  } catch (error) {
    console.error('获取院校数据失败:', error)
    message.error('获取院校数据失败')
  }
}
</script>
